﻿using System.Net.Http.Headers;

namespace NET8.Api.Middleware
{
    ///
    public class SwaggerAuthorizationMiddleware
    {
        private readonly RequestDelegate _next;

        ///
        public SwaggerAuthorizationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            // 检查是否是Swagger相关的请求路径

            if (context.Request.Path.StartsWithSegments("/swagger"))
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader != null && authHeader.StartsWith("Basic "))
                {
                    // Get the credentials from request header
                    var header = AuthenticationHeaderValue.Parse(authHeader);
                    var inBytes = Convert.FromBase64String(header.Parameter);
                    var credentials = Encoding.UTF8.GetString(inBytes).Split(':');
                    var username = credentials[0];
                    var password = credentials[1];

                    var loginUsername = AppSettingsHelper.Get("Login:username");
                    var loginPassword = AppSettingsHelper.Get("Login:password");

                    // validate credentials
                    if (username.Equals(loginUsername)
                      && password.Equals(loginPassword))
                    {
                        await _next.Invoke(context).ConfigureAwait(false);
                        return;
                    }
                }
                context.Response.Headers["WWW-Authenticate"] = "Basic";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                await _next.Invoke(context).ConfigureAwait(false);
            }
        }
    }
}